package org.nyt.medicalstore.service.impl;

import org.nyt.medicalstore.model.SaleRecord;
import org.nyt.medicalstore.repository.SaleRecordRepository;
import org.nyt.medicalstore.service.SaleRecordService;
import org.nyt.medicalstore.dto.SaleStatisticsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class SaleRecordServiceImpl implements SaleRecordService {
    @Autowired
    private SaleRecordRepository saleRecordRepository;

    @Override
    public SaleRecord saveSaleRecord(SaleRecord saleRecord) {
        return saleRecordRepository.save(saleRecord);
    }

    @Override
    public SaleRecord getSaleRecordById(Long id) {
        Optional<SaleRecord> saleRecord = saleRecordRepository.findById(id);
        return saleRecord.orElse(null);
    }

    @Override
    public List<SaleRecord> getAllSaleRecords() {
        return saleRecordRepository.findAll();
    }

    @Override
    public void deleteSaleRecord(Long id) {
        saleRecordRepository.deleteById(id);
    }

    @Override
    public List<SaleStatisticsDTO> getSalesStatistics(Date startDate, Date endDate) {
        return saleRecordRepository.getSalesStatistics(startDate, endDate);
    }

    @Override
    public List<SaleStatisticsDTO> getSalesRankingByQuantity(Date startDate, Date endDate) {
        List<SaleStatisticsDTO> rankings = saleRecordRepository.getSalesRankingByQuantity(startDate, endDate);
        // 添加排名
        for (int i = 0; i < rankings.size(); i++) {
            rankings.get(i).setRank(i + 1);
        }
        return rankings;
    }

    @Override
    public List<SaleStatisticsDTO> getSalesRankingByAmount(Date startDate, Date endDate) {
        List<SaleStatisticsDTO> rankings = saleRecordRepository.getSalesRankingByAmount(startDate, endDate);
        // 添加排名
        for (int i = 0; i < rankings.size(); i++) {
            rankings.get(i).setRank(i + 1);
        }
        return rankings;
    }
} 